package com.imageim.yimirror.ui.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetCallback;
import com.imageim.yimirror.common.network.tool.ParamCreator;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.util.PictureUtils;
import com.imageim.yimirror.common.util.UserUtil;
import com.martin.ads.omoshiroilib.util.BitmapUtils;
import com.theartofdev.edmodo.cropper.CropImageView;

import org.apache.http.message.BasicNameValuePair;
import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * 裁剪形象日记照片
 */
public class ClipPhotoActivity extends BaseActivity implements View.OnClickListener {

    private CropImageView cropImageView;
    private String photoPath;
    private boolean isUploading;
    private int aspectX = 9;
    private int aspectY = 16;

    @Override
    protected void initBundle() {
        photoPath = getIntent().getStringExtra("photoPath");
        boolean hasToDoAction = getIntent().hasExtra(Constants.TO_DO_FLAG);
        if (hasToDoAction) {
            toDoAction = getIntent().getIntExtra(Constants.TO_DO_FLAG, 0);
            if (toDoAction == Constants.Action.CLIP_BIG_SIZE_PHOTO) {
                aspectX = 480;
                aspectY = 855;
            } else if (toDoAction == Constants.Action.CLIP_SMALL_SIZE_PHOTO) {
                aspectX = 200;
                aspectY = 250;
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_clip_photo;
    }

    @Override
    protected void initView() {
        findViewById(R.id.btn_savepic).setOnClickListener(this);
        findViewById(R.id.btn_reshot).setOnClickListener(this);
        cropImageView = findViewById(R.id.crop_image_view);
        cropImageView.setAspectRatio(aspectX, aspectY);
        cropImageView.setFixedAspectRatio(true);
        cropImageView.setRotatedDegrees(90);
        cropImageView.setShowProgressBar(true);
        cropImageView.setGuidelines(CropImageView.Guidelines.OFF);
        cropImageView.setOnCropImageCompleteListener(new CropImageView.OnCropImageCompleteListener() {
            @Override
            public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) {
                //String path = FileUtil.saveBitmap(result.getBitmap());
                if (toDoAction == Constants.Action.CLIP_BIG_SIZE_PHOTO || toDoAction == Constants.Action.CLIP_SMALL_SIZE_PHOTO) {
                    // 返回用户的服装搭配图片bitmap
                    EventBus.getDefault().post(new EventMessage(EventCode.CODE_RETURN_CLIP_PHOTO, result.getBitmap()));
                    finish();
                } else {
                    // 上传形象相册
                    uploadDailyRecordPhoto(result.getBitmap());
                }
            }
        });
        clipImage();
    }

    private void clipImage() {
        //        Bitmap bitmap = BitmapUtils.loadBitmapFromFile(photoPath);
        //        Bitmap bitmap = PictureUtils.getImage(PictureUtils.compressAndReturnPath(photoPath, 90));
        //      bitmap = PictureUtils.rotateBitmap(270, bitmap);
        Bitmap bitmap = PictureUtils.getImage(photoPath);
        //        int bw = bitmap.getWidth();
        //        int bh = bitmap.getHeight();
        //        int left = (int) ((bw - bh * CameraPreviewActivity.preferedRatio) / 2);
        //        int top = 0;
        //        int redPacketHeight = bh;
        //        int redPacketWidth = (int) (redPacketHeight * CameraPreviewActivity.preferedRatio);
        //        Rect rect = new Rect(left, top, left + redPacketWidth, top + redPacketHeight);
        //        bitmap = BitmapUtils.clipBitmap(bitmap, rect);
        cropImageView.setImageBitmap(bitmap);
    }

    @Override
    protected void initData() {

    }

    // 上传形象日记照片
    private void uploadDailyRecordPhoto(final Bitmap photoBitmap) {
        if (isUploading) {
            return;
        }
        isUploading = true;
        List<BasicNameValuePair> params = new ParamCreator()
                .add(Constants.USER_ID, UserUtil.getUserId())
                .add("userPhoto", BitmapUtils.bitmapToBase64(photoBitmap, 95))
                .build();
        NetUtil.postObject(mContext, NetConstants.URL.UPLOAD_IMAGE_PHOTO, params, new NetCallback<String>() {
            @Override
            public void onStart() {
                showLoading();
            }

            @Override
            public void onSuccess(String result) {
                hideLoading();
                // TODO 显示替换背景页面
                EventBus.getDefault().post(new EventMessage(EventCode.CODE_SHOW_CHANGE_BG_FRAGMENT, null));
                EventBus.getDefault().post(new EventMessage(EventCode.CODE_UPDATE_CHANGE_BG_BITMAP, photoBitmap));
                finish();
                isUploading = false;
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                hideLoading();
                isUploading = false;
                toast(errorMsg + errorCode);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_savepic:
                cropImageView.getCroppedImageAsync();
                break;
            case R.id.btn_reshot:
                Bundle data = new Bundle();
                data.putInt(Constants.TO_DO_FLAG, toDoAction);
                SceneManager.toScene(mContext, TakeMomeryPhotoActivity.class, data);
                finish();
                break;
            default:
        }
    }
}